package com.rpc.servers;

import com.rpc.anoncations.RpcService;
import com.rpc.messages.MessageReq;
import com.rpc.utils.AnoncationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: pengjf
 * @Date: 2018-08-06 16:17
 * @Description:
 */
public class ServerProvider {
    private static Logger logger=LoggerFactory.getLogger(ServerSocket.class);

    public static void main(String[] args) throws Exception{
        Map<String,Object> map=AnoncationUtils.scanAnoncationClass("com.rpc.services.impls",RpcService.class);
        ServerSocket serverSocket=new ServerSocket(9000);
        logger.info("服务启动成功.....");
        Socket socket=serverSocket.accept();
        ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
        ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
        MessageReq req = (MessageReq) ois.readObject();
       // Class clazz = Class.forName(req.getClassName());
       // Object obj = clazz.newInstance();
        System.out.println(req.getClassName());
        logger.info("hello");
        Class clazz= (Class) map.get(req.getClassName());
        Object obj = clazz.newInstance();
        Method method=clazz.getDeclaredMethod(req.getMethod(),req.getArgsType());
        oos.writeObject(method.invoke(obj,req.getArgs()));
        logger.info("hello2");

        oos.flush();
        ois.close();
        oos.close();
        socket.close();
        logger.info("服务服务结束.....");


    }
}
